const jsLoader = (src: string) => {
  return new Promise<HTMLScriptElement>((resolve) => {
    const script = document.createElement('script')
    script.src = src
    script.type = 'text/javascript'
    script.onload = () => {
      resolve(script)
    }
    script.onerror = () => {
      resolve(script)
    }
    document.head.append(script)
  })
}
const cssLoader = (href: string) => {
  return new Promise<HTMLLinkElement>((resolve) => {
    const link = document.createElement('link')
    link.href = href
    link.rel = 'stylesheet'
    link.onload = () => {
      resolve(link)
    }
    link.onerror = () => {
      resolve(link)
    }
    document.head.append(link)
  })
}
const factory = () => {
  // <link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css"/>
  // <script src="//webapi.amap.com/maps?v=1.4.15&key=您申请的key值&"></script>
  // <script src="//webapi.amap.com/loca?v=1.3.2&key=您申请的key值"></script>
  // <script src="https://a.amap.com/Loca/static/mock/adcodes.js"></script>
  // <script src="https://a.amap.com/Loca/static/dist/jquery.min.js"></script>
  const cssArray = ['https://cache.amap.com/lbs/static/main1119.css']
  const jsArray = [
    '//webapi.amap.com/maps?v=1.4.15&key={key}', 
    '//webapi.amap.com/loca?v=1.3.2&key={key}', 
    'https://a.amap.com/Loca/static/mock/adcodes.js', 
    'https://a.amap.com/Loca/static/dist/jquery.min.js',
    '//webapi.amap.com/ui/1.1/main.js?v=1.1.1',
    // 'https://webapi.amap.com/loca?v=1.2.0&key={key}',
    // 'https://a.amap.com/Loca/static/mock/adcodes.js',
    // 'https://a.amap.com/Loca/static/dist/jquery.min.js',
  ]
  let elementArr: HTMLElement[] = []
  let order = 1
  return {
    async flush(amapKey: string) {
      order++
      const curr = order
      if (Array.isArray(elementArr) && elementArr.length > 0) {
        const old = elementArr
        elementArr = []
        for (const elt of old) {
          elt.remove()
        }
      }
      const tempArr: HTMLElement[] = []
      let t: HTMLElement | undefined
      for (const css of cssArray) {
        if (curr != order) {
          while (((t = tempArr.shift()), t)) {
            t.remove()
          }
          break
        }
        elementArr.push(await cssLoader(css))
      }
      for (const js of jsArray) {
        if (curr != order) {
          while (((t = tempArr.shift()), t)) {
            t.remove()
          }
          break
        }
        elementArr.push(await jsLoader(js.replace('{key}', amapKey)))
      }
    }
  }
}

export const amapDependencies = factory()
